package com.mifengs.commonbase.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by lihaoqi on 2017/8/28.
 */

public class DeviceInfoUtil {
    private static final String TAG = "DeviceInfoUtil";

    /**
     * Get screen width
     *
     * @param context
     * @return
     */
    public static int getWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        int width = dm.widthPixels;
        return width;
    }

    /**
     * Get screen height
     *
     * @param context
     * @return
     */
    public static int getHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        int height = dm.heightPixels;
        return height;
    }

    /**
     * Get the device's id
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        final TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId=null;
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        }
        deviceId = tm.getDeviceId();
        return deviceId == null ? "unknown" : deviceId;
    }

    /**
     * Get the app's version(1.0 versionName)
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        String version = "";
        try {
            PackageManager pm = context.getPackageManager();

            PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            version = pinfo.versionName;
            // Strint versionName = pinfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            String msg = e.getMessage() == null ? e.toString() : e.getMessage();
            LogUtil.e(TAG, msg);
        }
        return version;
    }

    public static int getAppCode(Context context) {
        int version = 0;
        try {
            PackageManager pm = context.getPackageManager();

            PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            version = pinfo.versionCode;
            // Strint versionName = pinfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            String msg = e.getMessage() == null ? e.toString() : e.getMessage();
            LogUtil.e(TAG, msg);
        }
        return version;
    }

    /**
     * Get the platform (such as 2.3)
     *
     * @param context
     * @return
     */
    public static String getPlatformVersion(Context context) {
        return Build.VERSION.RELEASE;
    }

    public static String getDeviceModel(Context context) {
        return Build.MODEL+" "+getPlatformVersion(context);

    }

    /**
     * Get the API level (API 8,9,10,11,...,17)
     *
     * @param context
     * @return
     */
    public static int getPlatformApiLevel(Context context) {
        int version = Integer.parseInt(Build.VERSION.SDK);
        return version;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getAndroidId(Context context) {
        String ANDROID_ID = Settings.System.getString(
                context.getContentResolver(), Settings.System.ANDROID_ID);
        return ANDROID_ID == null ? "unknown" : ANDROID_ID;
    }

    /**
     * Get the phone's info
     *
     * @param context
     * @return A JSON object which included the phone info.
     */
    public static JSONObject getPhoneInfo(Context context) {
        JSONObject obj = new JSONObject();
        try {
            String deviceId = getDeviceId(context);
            // String serialNo = android.os.Build.SERIAL + "_" + deviceId;
            obj.put("platform_version", getPlatformVersion(context));
            obj.put("platform_api_level", getPlatformApiLevel(context));
            obj.put("app_version", getAppVersion(context));

            /** Some kind of device return unknown , such as Nexus 7 */
            obj.put("device_id", deviceId);
            /** Will be different when reinstall android system */
            obj.put("android_id", getAndroidId(context));
            /** Need android 2.3 and above */
            obj.put("serial_no", getSerialNo(context));

            obj.put("model", Build.MODEL);
            obj.put("board", Build.BOARD);
            obj.put("bootloader", Build.BOOTLOADER);
            obj.put("cpu_abi", Build.CPU_ABI);
            obj.put("cpu_abi2", Build.CPU_ABI2);
            obj.put("device", Build.DEVICE);
            obj.put("display", Build.DISPLAY);
            obj.put("fingerprint", Build.FINGERPRINT);
            obj.put("hardware", Build.HARDWARE);
            obj.put("host", Build.HOST);
            obj.put("manufacturer", Build.MANUFACTURER);
            obj.put("product", Build.PRODUCT);
            obj.put("user", Build.USER);
            obj.put("screen_width", getWidth(context));
            obj.put("screen_height", getHeight(context));
        } catch (JSONException e) {
            LogUtil.e(TAG, e);
        }
        return obj;
    }

    /**
     * Get phone's serial no
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String getSerialNo(Context context) {
        if (Build.VERSION.SDK_INT > 8
                && !Build.SERIAL.equals("unknown"))
            return Build.SERIAL;
        else
            return getDeviceId(context);

    }
}
